package com.Khan.Controller;

import com.Khan.Service.FileService;
import com.Khan.pojo.Efile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Khan Liu
 * @date 2022/2/14 17:47
 */
@Controller
public class FileUploadController {

    @Autowired
    FileService fileService;

    @Value("${spring.web.upload-path}")
    private String uploadPath;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @RequestMapping(value = "/uploadFile")
    public String uploadPage() {
        return "uploadFile";
    }

    @RequestMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ModelAndView upload(@RequestParam("file") MultipartFile file, ModelAndView model, HttpServletRequest request) {
        model.setViewName("uploadFile.html");
        //判断文件是否为空
        if (file.isEmpty()) {
            model.addObject("result_file", "文件为空");
            return model;
//            model.addAttribute("result_file", "文件为空");
//            return "upload";
        }

        //创建输入输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {

            String format = sdf.format(new Date());
            File folder = new File(uploadPath + format);
            if (!folder.isDirectory()) {
                folder.mkdir();
            }
            inputStream = file.getInputStream();

            String fileName = file.getOriginalFilename();
            long fileSize = file.getSize();
            String uuid = UUID.randomUUID().toString();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);

            File targetFile = new File(folder + "/" + uuid + "." + fileType);
            if (!targetFile.exists()) {
                targetFile.getParentFile().mkdir();
                try {
                    //创建文件
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            outputStream = new FileOutputStream(targetFile);
            FileCopyUtils.copy(inputStream, outputStream);

            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + format + "/" + uuid + "." + fileType;
            fileService.saveFile(new Efile(uuid, fileName, fileType, fileSize, filePath, new Date()));

//            model.addAttribute("result_file", "上传成功");
            model.addObject("result_file", "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
//            model.addAttribute("result_file", "上传失败");
            model.addObject("result_file", "上传失败");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

//        return "upload";

        return model;

    }

    @GetMapping("/getFile/{uuid}")
    @ResponseBody
    public String getFile(@PathVariable("uuid") String uuid) {
        Efile file = fileService.getFileByUUID(uuid);
        if(file == null){
            return "";
        }
        return file.getFilePath();
    }

    @GetMapping("/getJson/{uuid}")
    @ResponseBody
    public String getJson(@PathVariable("uuid") String uuid) {
        Efile file = fileService.getFileByUUID(uuid);
        if(file == null){
            return "";
        }
        return file.toString();
    }


}

